package logController;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Observable;
import java.util.Queue;
import java.util.Stack;

/**
 * @date Apr. 20, 2012
 * @author Francisco J. Martínez
 */
public class Log  extends Observable{
	
	/** Debug mode activated */
	private boolean mDebugMode;
	/** Messages not read yet */
	private Queue<LogMessage> mUnread;
	/** Messages already have been read and notified to Observers */
	private Stack<LogMessage> mHistory;
	
	/**
	 * Implements pattern design singleton
	 */
	static private Log mSingleton = null;
	
	/**
	 * Private Constructor to initialize 
	 */
	private Log(){
		mUnread = new LinkedList<LogMessage>();
		mHistory = new Stack<LogMessage>();
		mDebugMode = false;
	}
	
	/**
	 * Implementation of Desing pattern singleton. No params are needed.
	 * @return A singleton instance of Log
	 */
	static public Log getInstance(){
		if(mSingleton ==null){
			mSingleton = new Log();
		}
		return mSingleton;
	}

	/**
	 * Set the new debug mode
	 * @param value
	 */
	public void setDebugMode(boolean value) {
		mDebugMode = value;
	}

	/**
	 * Show the current mode is already activated
	 * @return True if Debug mode on, false otherwise
	 */
	public boolean showDebugMessages() {
		return mDebugMode;
	}

	/**
	 * Return a copy a unread messages, and store this messages in mHistory 
	 * @return A List of messages that already have not been notified to observers
	 */
	public List<LogMessage> getUnreadMessages() {
		LinkedList<LogMessage> res;
		// Creo el objeto a devolver
		res = new LinkedList<LogMessage>(mUnread);
		// Paso los leídos al historial
		mHistory.addAll(mUnread);
		// Borrar tambien mUnread
		mUnread = new LinkedList<LogMessage>();
		return res;
	}

	/**
	 * Add a new message to unread list.
	 * @param message New message
	 */
	public void addMessage(LogMessage message) {
		mUnread.add(message);
		setChanged();
		notifyObservers();
	}
	
	
	/**
	 * @return All messages allocated in mHistory into a String
	 */
	public String toText(){
		String res="";
		for(LogMessage elem : mHistory){
			res=res+elem.toString()+"\n";
		}
		return res;
	}
	
	/**
	 * @param nElems Lines to return
	 * @return nElems messages into a String, if not exists enough messages return all mHistory.
	 */
	public String toText(int nElems){
		String res="";
		int i=0;
		Iterator<LogMessage> iter = mHistory.iterator();
		
		while(i<nElems){
			if(iter.hasNext()){
				res=res+iter.next().toString()+"\n";
				i++;
			}else{
				break;
			}
		}		
		return res;
	}
}
